package cn.haoran.common.utils;

import cn.haoran.common.exception.AppException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传工具
 * Create by hanran on 2019/7/24
 */
public class FileUtils {
    public static String saveFile(MultipartFile file, String phyPath, String type) throws Exception {
        String originalFileName, newFileName, url;
        File newFile;
        String date = DateUtils.format(new Date()) + "/";
        //上传文件名
        originalFileName = file.getOriginalFilename();
        // UUID + .png
        newFileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
        // 创建空file
        newFile = new File(phyPath + date + newFileName);
        if(!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        // multipartFile to file
        file.transferTo(newFile);
        // url = type + "/" + date + newFileName;
        url = date + newFileName;
        return url;
    }

    public static void deleteFile(String path) throws Exception {
        File file = new File(path);
        if(!file.exists() || !file.isFile()) {
            throw new AppException("服务端文件不存在！");
        }
        file.delete();
    }
}
